/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package services;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.text.DecimalFormat;
import java.util.Random;

/**
 *
 * @author ntfsbk
 */
public class Ultility {

    private final static int MIN_PORT_NUMBER = 1024;
    private final static int MAX_PORT_NUMBER = 9999;
    private static Random arandom=new Random();
    /*
     * create a random integer range from aStart to
     *
     */

    public static int randomInteger(int aStart, int aEnd, Random aRandom) {
        if (aStart > aEnd) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        //get the range, casting to long to avoid overflow problems
        long range = (long) aEnd - (long) aStart + 1;
        // compute a fraction of the range, 0 <= frac < range
        long fraction = (long) (range * aRandom.nextDouble());
        int randomNumber = (int) (fraction + aStart);

        return randomNumber;
    }

    public static int random() {
        while(true){
            int port=randomInteger(MIN_PORT_NUMBER,MAX_PORT_NUMBER , arandom);
            boolean available=available(port, MIN_PORT_NUMBER, MAX_PORT_NUMBER);
            if(available){
                return port;
            }
        }
    }

    /**
     * Checks to see if a specific port is available.
     *
     * @param port the port to check for availability
     */
    public static boolean available(int port, int MIN_PORT_NUMBER, int MAX_PORT_NUMBER) {
        if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
            throw new IllegalArgumentException("Invalid start port: " + port);
        }

        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        } finally {
            if (ds != null) {
                ds.close();
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /*
                     * should not be thrown
                     */
                }
            }
        }

        return false;
    }
    
    public static String convertMem(float bSize){
        DecimalFormat form=new DecimalFormat("0.00");
        String s=new String();
        float kSize=bSize / 1024; 
        if(kSize < 1024){
            s=form.format(kSize)+"KB";
        }
        else if(kSize < (1024*1024)){
            s=form.format(kSize/1024)+"MB";
        }
        else {
            s=form.format(kSize/(1024*1024))+"GB";
        }
        return s;
    }
}
